package com.yinhanshi.s3test.sign;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.yinhanshi.s3test.http.ApiRetrofit;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 标题：文件下载类
 * 作者：yinhanshi .
 * 时间：2020/3/8 .
 */
public class SignDownloader {

    private boolean userInterrupted = false;
    private boolean userAborted = false;
    private DownloadProgressListener uploadProgressListener;
    private static SignUploader instance;

    private String signUrl;
    private File downloadFile;
    private long startIndex;
    private long endIndex;


    /**
     * 下载文件
     *
     * @param uploadProgressListener 回调
     * @param signUrl                安全令牌
     * @param downloadFile           存储文件
     * @param endIndex               下载终点位置
     */
    public SignDownloader(DownloadProgressListener uploadProgressListener,
                          String signUrl, File downloadFile,
                          long endIndex) {
        this.uploadProgressListener = uploadProgressListener;
        this.signUrl = signUrl;
        this.downloadFile = downloadFile;
        this.startIndex = downloadFile.length();
        this.endIndex = endIndex;
    }

    /**
     * 下载文件
     *
     * @param uploadProgressListener 回调
     * @param signUrl                安全令牌
     * @param downloadFile           存储文件
     * @param startIndex             下载起始位置
     * @param endIndex               下载终点位置
     */
    public SignDownloader(DownloadProgressListener uploadProgressListener,
                          String signUrl, File downloadFile,
                          long startIndex, long endIndex) {
        this.uploadProgressListener = uploadProgressListener;
        this.signUrl = signUrl;
        this.downloadFile = downloadFile;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
    }

    public void start() {
        ApiRetrofit.getInstance().downloadFile("", startIndex, endIndex)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
    }

    public interface DownloadProgressListener {
        /**
         * 下载回调
         *
         * @param bytesDownloaded 已下载字节数
         * @param percentUploaded 已下载百分比
         * @param netSpeed        实时下载网速
         */
        public void progressChanged(long bytesDownloaded, int percentUploaded, long netSpeed);
    }

}
